import dayjs from 'dayjs'

/**
 * 计算距离指定日期还有多久
 * @param targetDate 目标日期字符串
 * @returns 计算结果的对象
 */
export function useCountdown(targetDate: string) {
  const countdown = ref<{ days: number, hours: number, minutes: number, seconds: number }>({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0
  })
  let animationFrameId: number | null = null

  const updateCountdown = () => {
    const now = dayjs()
    const targetTime = dayjs(targetDate)
    const diff = targetTime.diff(now)

    if (diff <= 0) {
      countdown.value = { days: 0, hours: 0, minutes: 0, seconds: 0 }
      cancelAnimationFrame(animationFrameId!)
      animationFrameId = null
      return
    }

    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((diff % (1000 * 60)) / 1000)

    countdown.value = { days, hours, minutes, seconds }

    animationFrameId = requestAnimationFrame(updateCountdown)
  }

  onMounted(() => {
    updateCountdown()
  })

  onUnmounted(() => {
    if (animationFrameId !== null) {
      cancelAnimationFrame(animationFrameId)
      animationFrameId = null
    }
  })

  return countdown
}
